package com.cj.myblog.interceptor;

import com.cj.myblog.common.util.FileUtils;
import com.cj.myblog.constants.Constants;
import com.cj.myblog.dao.ArticleRepository;
import com.cj.myblog.model.ArticleDo;
import com.cj.myblog.plugin.StringTemplate;
import com.cj.myblog.service.PartService;
import com.xiaoleilu.hutool.util.ClassUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017-08-30.
 */
public class WebMvcInterceptor implements HandlerInterceptor{


    @Autowired
    private PartService partService;

    @Autowired
    private ArticleRepository articleRepository;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, final ModelAndView modelAndView) throws Exception {
        if (modelAndView != null){
            String  viewPath = modelAndView.getViewName();

            //阅读量计数器
            if(StrUtil.isNotEmpty(viewPath) &&
                    StrUtil.containsIgnoreCase(viewPath,"front/view")){
                HttpSession session = request.getSession();
                Object artIdObj = session.getAttribute("artIdSet");
                Map<Long,Long> artIdMap =
                        artIdObj == null ?
                                new HashMap<Long,Long>() : (Map<Long,Long>) artIdObj;
                ArticleDo articleDo = (ArticleDo) modelAndView.getModel().get("view");
                boolean isUpdate = false;

                if (artIdMap.get(articleDo.getId()) == null){
                    articleDo.setHits(articleDo.getHits() +1);
                    artIdMap.put(articleDo.getId(),System.currentTimeMillis());
                    isUpdate = true;
                }else {
                    final Long longTime = 3600000L;
                    Long artTime = artIdMap.get(articleDo.getId());
                    Long nowTime = System.currentTimeMillis();
                    if (nowTime - artTime > longTime){
                        articleDo.setHits(articleDo.getHits() +1);
                        artIdMap.put(articleDo.getId(),System.currentTimeMillis());
                        isUpdate = true;
                    }
                }

                if (isUpdate){
                    session.setAttribute("artIdSet",artIdMap);
                    articleRepository.save(articleDo);
                }

            }

            //前端页面
            if(StrUtil.isNotEmpty(viewPath) &&
                    StrUtil.containsIgnoreCase(viewPath,"front")){
                String theme = Constants.options.get("theme").toString();
                List<String> viewPathList = StrUtil.split(viewPath,'/');
                viewPathList.add(1,"theme/"+theme);
                //设置要显示的模板view
                modelAndView.setViewName(StrUtil.join("/",viewPathList));
                //放入网站属性
                modelAndView.addObject("partList",partService.findByStatus(Constants.ONE));
                modelAndView.addObject("web",Constants.options);
                modelAndView.addObject("themePath","/theme/"+theme);
            }

            //插件
            if(StrUtil.isNotEmpty(viewPath) &&
                    StrUtil.containsIgnoreCase(viewPath, "plugins/admin")){
                List<String> viewPathList = StrUtil.split(viewPath,'/');
                modelAndView.addObject("pluginPath", "/templates/plugins/" +viewPathList.get(2));
                //去掉admin,front
                viewPathList.remove(1);

                //modelAndView.setViewName("/templates/plugins/test/index");


                View view = new View() {
                    @Override
                    public String getContentType() {
                        return "text/html";
                    }

                    @Override
                    public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

                        String testPath = "E:\\javaworkspace\\myblog\\blog\\target\\blog-1.0\\WEB-INF\\lib\\" +"test-1.0-SNAPSHOT.jar";

                        String content = FileUtils.getJarFileContent(new File(testPath),"templates/plugins/test/index.ftl");

                        Configuration cfg = new Configuration();
                        cfg.setTemplateLoader(new StringTemplate(content));
                        cfg.setDefaultEncoding("UTF-8");

                        Template template = cfg.getTemplate("");

                        StringWriter tplWriter = new StringWriter();
                        template.process(modelAndView.getModel(), tplWriter);

                        response.getWriter().write(tplWriter.toString());

                    }
                };

                modelAndView.setView(view);

            }


        }

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
